package cn.hebutrun.oulabot.service.impl;

import cn.hebutrun.oulabot.common.CustomException;
import cn.hebutrun.oulabot.entity.OulaFile;
import cn.hebutrun.oulabot.mapper.OulaFileMapper;
import cn.hebutrun.oulabot.service.IOulaFileService;
import cn.hutool.core.io.FileTypeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * oula文件表 服务实现类
 *
 * @author Adai
 * @since 2022-10-10
 */
@Service
public class OulaFileServiceImpl extends ServiceImpl<OulaFileMapper, OulaFile>
    implements IOulaFileService {

  @Override
  public boolean upload(MultipartFile[] files) {
    if (files == null || files.length == 0) {
      throw new CustomException("上传失败，文件为空！");
    }

    List<OulaFile> oulaFiles =
        Arrays.stream(files)
            .map(
                file -> {
                  try {
                    byte[] bytes = file.getBytes().clone();
                    String originalFilename = file.getOriginalFilename();
                    Optional.ofNullable(originalFilename)
                        .orElseThrow(() -> new CustomException("文件名为空"));
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                    File tempFile = File.createTempFile(originalFilename, suffix);
                    file.transferTo(tempFile);
                    String type = FileTypeUtil.getType(tempFile);
                    return new OulaFile()
                        .setFileName(
                            originalFilename.substring(0, originalFilename.lastIndexOf(".") + 1)
                                + type)
                        .setFileData(bytes)
                        .setFileType(type);
                  } catch (IOException e) {
                    throw new CustomException(e.getMessage());
                  }
                })
            .toList();

    return this.saveBatch(oulaFiles);
  }
}
